<route lang="json5">
  {
    style: {
      navigationBarTitleText: '订单详情',
    },
  }
  </route>
<template>
  <view class="page">


    <!-- 倒计时提示 -->
    <!-- <view v-if="orderDetail.status == 1" class="countdown">
      <text>还剩</text>
      <text class="time">{{ countdownTime }}</text>
      <text>订单自动取消</text>
    </view> -->

    <!-- 收货地址 -->
    <view class="address-card">
      <view class="address-info">
        <view class="user-info">
          <text class="name">{{ orderDetail.ship_name }}</text>
          <text class="phone">{{ orderDetail.ship_mobile }}</text>
        </view>
        <text class="address-detail">{{ orderDetail.ship_address }}</text>
      </view>
      <view class="edit-btn cursor-pointer">
        <!-- <text>修改</text> -->
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="goods-card">
      <view class="shop-name">
        <text class="tag">自营</text>
        <text>宝道商贸</text>
      </view>
      <view class="goods-info">
        <image class="goods-img" :src="orderGoods.length > 0 ? orderGoods[0]?.image : ''" mode="aspectFill" />
        <view class="goods-detail">
          <view class="goods-title">{{ orderGoods.length > 0 ? orderGoods[0].name : '' }}</view>
          <view class="goods-spec" v-if="orderGoods.length > 0 && orderGoods[0].spes.length > 0">规格：{{
            orderGoods[0].spes }}
          </view>
          <view class="goods-price flex">
            <text>¥{{ orderGoods.length > 0 ? orderGoods[0].price : '' }}</text>
            <view class="goods-num text-gray-500 mx-2">
              <text>x</text>
              <text>{{ orderGoods.length > 0 ? orderGoods[0].nums : '' }}</text>
            </view>
          </view>

        </view>
      </view>

    </view>



    <!-- 订单信息 -->
    <view class="order-info">
      <view class="info-item">
        <text class="label">订单编号</text>
        <text class="value">{{ orderDetail.order_sn }}</text>
      </view>
      <!-- <view class="info-item">
        <text class="label">支付方式</text>
        <text class="value">微信支付</text>
      </view> -->
      <view class="info-item text-right">
        <view class="pay-price">
          <text>总金额：</text>
          <text class="amount">¥ {{ orderDetail.order_amount }}</text>
        </view>
      </view>
      <!-- <view class="info-item cursor-pointer">
        <text class="label">发票信息</text>
        <uni-icons type="right" size="16"/>
      </view> -->
    </view>

    <!-- 底部支付栏 -->
    <view v-if="orderDetail.status == 1 || orderDetail.status == 2" class="bottom-bar flex justify-between">
      <!-- <view v-if="orderDetail.status == 1 || orderDetail.status == 2" class="text-gray-500 cursor-pointer"
        @click="cancelOrder">
        取消订单
      </view> -->
      <!-- <button v-if="orderDetail.status == 1" class="pay-btn cursor-pointer" @click="payOrder">立即支付</button> -->
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { getOrderDetailAPI, postOldOrderPayAPI, postOrderCancelAPI } from '@/service/index/index'
import { useRoute } from 'vue-router'
import safeArea from '@/components/safeArea.vue'
const countdownTime = ref('00:00:00');
let timer: number;
const route = useRoute()
const id = ref(0)
const order_sn = ref('')
const updateCountdown = () => {
  const [hours, minutes, seconds] = countdownTime.value.split(':').map(Number);
  let totalSeconds = hours * 3600 + minutes * 60 + seconds;

  timer = setInterval(() => {
    totalSeconds -= 1;
    if (totalSeconds <= 0) {
      clearInterval(timer);
      return;
    }

    const h = Math.floor(totalSeconds / 3600);
    const m = Math.floor((totalSeconds % 3600) / 60);
    const s = totalSeconds % 60;

    countdownTime.value = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  }, 1000);
};

const orderDetail = ref({})
const payInfo = ref({})
const isNeedPay = ref(false)
const orderGoods = ref([])

const handlePay = async () => {
  const res = await postOldOrderPayAPI({
    id: id.value
  })
  if (res.code === 1) {
    payInfo.value = res.data.pay_info
    isNeedPay.value = res.data.need_pay
  } else {
    // uni.showToast({
    //   title: res.msg,
    //   icon: 'none',
    // })
  }

};
const cancelOrder = async () => {
  const res = await postOrderCancelAPI({
    id: id.value
  })
  console.log('res', res)
  if (res.code === 1) {
    uni.showToast({
      title: '取消订单成功',
      icon: 'success',
    })
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
  }
}
const payOrder = () => {
  //#ifdef APP_PLUS || MP_WEIXIN
  if (isNeedPay.value) {
    wx.requestPayment({
      timeStamp: payInfo.value.timestamp,
      nonceStr: payInfo.value.nonceStr,
      package: payInfo.value.package,
      signType: payInfo.value.signType,
      paySign: payInfo.value.paySign,
      success(res) {
        console.log('Payment successful', res)
        uni.showToast({
          title: '支付成功！',
          icon: 'success',
        })
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/my/order' })
        }, 1000)
      },
      fail(err) {
        console.error('Payment failed', err)
        uni.showToast({
          title: '支付失败，请重试',
          icon: 'none',
        })
      },
    })
  }
  //#endif
  //#ifdef H5

  uni.showToast({
    title: '请在小程序端付款',
    icon: 'none',
  })
  //#endif

}
const getOrderDetail = async () => {
  const res = await getOrderDetailAPI({
    id: id.value,
    sn: order_sn.value
  })
  if (res.code === 1) {
    orderDetail.value = res.data.order
    orderGoods.value = res.data.goods

    // Convert auto_cancel_time from seconds to HH:MM:SS format
    if (res.data.order.cancel_remain_time > 0) {
      const totalSeconds = parseInt(res.data.order.cancel_remain_time);
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;

      countdownTime.value = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
      updateCountdown();

    }
  }
}
//#ifdef APP_PLUS || MP_WEIXIN
onLoad((options) => {
  id.value = options.id
  order_sn.value = options.sn
  getOrderDetail()
  handlePay()
})
onUnload(() => {
  clearInterval(timer);
})
//#endif
//#ifdef H5
onMounted(() => {
  id.value = route.query.id
  order_sn.value = route.query.sn
  getOrderDetail();
  handlePay();
});
onUnmounted(() => {
  clearInterval(timer);
});
//#endif


</script>

<style>
page {
  height: 100%;
  background-color: #f5f5f5;
}

.page {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.nav {
  display: flex;
  align-items: center;
  height: 88rpx;
  background-color: #ffffff;
  padding: 0 30rpx;
}

.nav-left {
  width: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
}

.nav-right {
  width: 40rpx;
  display: flex;
  justify-content: flex-end;
}

.countdown {
  height: 60rpx;
  background-color: #fff7cc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.countdown .time {
  color: #ff4d4f;
  margin: 0 10rpx;
}

.address-card {
  margin-top: 20rpx;
  padding: 30rpx;
  background-color: #ffffff;
  display: flex;
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.user-info {
  margin-bottom: 10rpx;
}

.name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 20rpx;
}

.phone {
  font-size: 14px;
  color: #666666;
}

.address-detail {
  font-size: 14px;
  color: #333333;
  line-height: 1.4;
}

.edit-btn {
  margin-left: 20rpx;
  color: #666666;
  font-size: 14px;
}

.goods-card {
  margin-top: 20rpx;
  background-color: #ffffff;
  padding: 30rpx;
}

.shop-name {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.tag {
  background-color: #ff4d4f;
  color: #ffffff;
  font-size: 12px;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
}

.goods-info {
  display: flex;
  margin-bottom: 20rpx;
}

.goods-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
}

.goods-detail {
  flex: 1;
  margin-left: 20rpx;
}

.goods-title {
  font-size: 14px;
  color: #333333;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.goods-spec {
  font-size: 12px;
  color: #999999;
  margin-bottom: 10rpx;
}

.goods-price {
  color: #ff4d4f;
  font-size: 16px;
  font-weight: 500;
}

.plus-tag {
  background-color: #fff1f0;
  color: #ff4d4f;
  font-size: 12px;
  padding: 10rpx 20rpx;
  display: inline-block;
  border-radius: 4rpx;
}

.price-detail {
  margin-top: 20rpx;
  background-color: #ffffff;
  padding: 30rpx;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  font-size: 14px;
  color: #666666;
}

.plus-discount,
.plus-free {
  color: #ff4d4f;
}

.total-price {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1px solid #f5f5f5;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-size: 14px;
}

.total-price .price {
  color: #ff4d4f;
  margin: 0 20rpx;
}

.order-info {
  margin-top: 20rpx;
  background-color: #ffffff;
  padding: 30rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 14px;
}

.info-item .label {
  color: #666666;
}

.info-item .value {
  color: #333333;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.pay-price {
  flex: 1;
  font-size: 14px;
}

.pay-price .amount {
  color: #ff4d4f;
  font-size: 20px;
  font-weight: 500;
}

.pay-btn {
  width: 200rpx;
  height: 72rpx;
  line-height: 72rpx;
  background-color: #ff4d4f;
  color: #ffffff;
  font-size: 16px;
  border-radius: 36rpx;
  margin: 0;
}

.cursor-pointer {
  cursor: pointer;
}
</style>
